package bosc.cn.service.wallet.impl;

import bosc.cn.constant.WalletConstants;
import bosc.cn.dto.common.CommonResponse;
import bosc.cn.dto.common.ResponseWrapper;
import bosc.cn.service.wallet.WalletRegisterService;
import bosc.cn.service.wallet.bo.WalletRegisterReqBO;
import bosc.cn.service.wallet.bo.WalletRegisterResBO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import mapper.UserInfoMapper;
import mapper.WalletInfoMapper;
import mapper.WalletUserInfoMapper;
import model.UserInfo;
import model.WalletInfo;
import model.WalletUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class WalletRegisterServiceImpl implements WalletRegisterService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WalletInfoMapper walletInfoMapper;

    @Autowired
    private WalletUserInfoMapper walletUserInfoMapper;

    @Override
    public ResponseWrapper<WalletRegisterResBO> walletRegister(WalletRegisterReqBO reqBO) {

        ResponseWrapper<WalletRegisterResBO> resBO = new ResponseWrapper<>();
        CommonResponse head = new CommonResponse();
        WalletRegisterResBO body = new WalletRegisterResBO();


        try {

            // 正常通信
            head.setRetCd("000000");
            head.setRetMsg("通信成功");
            head.setRetTm(LocalDateTime.now());

            // 根据 userId 查询
//            UserInfo user = userInfoMapper.selectOne(
//                    new QueryWrapper<UserInfo>()
//                            .eq("user_id", reqBO.getUserId())
//            );

//            // 校验用户是否存在
//            if (user == null) {
//                body.setPrcSts("PR99");
//                body.setPrcMsg("用户不存在");
//                resBO.setHead(head);
//                resBO.setBody(body);
//                return resBO;
//            }
//
//            // 校验用户状态是否正常
//            if (!WalletConstants.USER_STATUS_ACTIVE.equals(user.getUserStatus())) {
//                body.setPrcSts("PR88");
//                body.setPrcMsg("用户状态异常");
//                resBO.setHead(head);
//                resBO.setBody(body);
//                return resBO;
//            }

            // 查询钱包信息表
            WalletInfo wallet = walletInfoMapper.selectOne(
                    new QueryWrapper<WalletInfo>()
                            .eq("wlt_id", reqBO.getWltId())
            );

            if(wallet == null) {
                log.info("钱包信息未登记，钱包id：{}", reqBO.getWltId());
                // 第一次登记，插入钱包信息表
                wallet = new WalletInfo();
                wallet.setWltId(reqBO.getWltId());
                wallet.setWltName(reqBO.getCstNm());
                wallet.setCstNm(reqBO.getCstNm());
                wallet.setCstIdentTp(reqBO.getCstIdentTp());
                wallet.setCstNo(reqBO.getCstNo());
                wallet.setOprNm(reqBO.getOprNm());
                wallet.setOprIdentTp(reqBO.getOprIdentTp());
                wallet.setOprIdentNo(reqBO.getOprIdentNo());
                wallet.setOprMblNo(reqBO.getOprMblNo());

                wallet.setWltSts(WalletConstants.Status.WS01);
                wallet.setWltLvl(WalletConstants.Level.WL04);
                wallet.setWltType(WalletConstants.Type.WT09);
                wallet.setWltBnk(WalletConstants.WALLET_BANK_BOS);
                wallet.setWltBal(BigDecimal.ZERO);
                wallet.setWltBalLmt(WalletConstants.WALLET_BAL_LIMIT);
                wallet.setSngLmtAmt(WalletConstants.WALLET_SINGLE_LIMIT);
                wallet.setDlyLmtAmt(WalletConstants.WALLET_DAILY_LIMIT);
                wallet.setYrLmtAmt(WalletConstants.WALLET_YEARLY_LIMIT);
                wallet.setCreateTime(LocalDateTime.now());
                wallet.setLastUpdateTime(LocalDateTime.now());
                wallet.setLastUpdateOperate("钱包初始化");

                String authDt = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                wallet.setWltAuthDt(authDt);

                walletInfoMapper.insert(wallet);
            }else{
                log.info("钱包信息已登记，钱包id：{}", reqBO.getWltId());

            }

            // 查询领用登记表
            WalletUserInfo walletuser = walletUserInfoMapper.selectOne(
                    new QueryWrapper<WalletUserInfo>()
                            .eq("wlt_id", reqBO.getWltId())
                            .eq("user_id", reqBO.getUserId())
            );

            if(walletuser != null){
                log.info("该用户已登记领用该钱包，钱包id：{}，用户id：{}", reqBO.getWltId(), reqBO.getUserId());
                body.setPrcSts("PR99");
                body.setPrcMsg("该用户已登记领用该钱包，无须重复登记");
                resBO.setHead(head);
                resBO.setBody(body);
                return resBO;
            }

            // 插入领用登记表
            walletuser = new WalletUserInfo();
            walletuser.setWltId(wallet.getWltId());
            walletuser.setUserId(reqBO.getUserId());
            walletuser.setSubWltKey(reqBO.getSubWltKey());
            walletuser.setCstNo(reqBO.getCstNo());
            walletuser.setCreateTime(LocalDateTime.now());
            walletuser.setLastUpdateTime(LocalDateTime.now());
            walletuser.setLastUpdateOperate("钱包领用登记");

            walletUserInfoMapper.insert(walletuser);

            // 封装响应返回
            body.setPrcSts("PR00");
            body.setPrcMsg("登记成功");


        } catch (Exception e) {
            log.error("系统异常：{}", e.getMessage());
            // 出现异常，通信失败
            head.setRetCd("999999");
            head.setRetMsg("系统异常：" + e.getMessage());
            head.setRetTm(LocalDateTime.now());
        }

        resBO.setHead(head);
        resBO.setBody(body);
        return resBO;

    }
}
